<template>
    <el-dialog :close-on-click-modal="false"  ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="90%"
        :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="巡查点名称 :" prop="inspectionPointName">
                        <el-input v-model="ruleForm.inspectionPointName" placeholder="请输入巡查点名称" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="关联设施" prop="facilityNoList">
                        <el-select class="w100p" v-model="ruleForm.facilityNoList" clearable filterable multiple
                            placeholder="请选择设施名称">
                            <el-option v-for="(item, index) in facilityList" :key="index" :label="item.facilityName"
                                :value="item.facilityNo" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="允许误差范围" prop="errorRange">
                        <el-input v-model="ruleForm.errorRange" placeholder="请输入误差范围值(米)" clearable>
                            <template slot="append">米</template>
                        </el-input>
                    </el-form-item></el-col>
                <el-col :span="12">
                    <el-form-item label="编号 :" prop="inspectionPointCode" :required="true">
                        <el-input v-model="ruleForm.inspectionPointCode" placeholder="请输入编号" clearable />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="12">
                    <el-form-item label="经度" prop="longitude">
                        <el-input v-model="ruleForm.longitude">

                            <template slot="append">°</template>
                        </el-input>
                    </el-form-item></el-col>
                <el-col :span="12">
                    <el-form-item label="纬度" prop="latitude">
                        <el-input v-model="ruleForm.latitude">

                            <template slot="append">°</template>
                        </el-input>
                    </el-form-item></el-col>
            </el-row>
            <el-form-item label="地图">
                <MapPoint :isOnePoint="true" v-loading="loading" ref="mapPoint" @getMarker="getMarker" :isShowSearch="true"></MapPoint>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
    </el-dialog>
</template>

<script>
import patrolInfoManage from "@/api/patrol-info-manage/patrol-point-manage";
import MapPoint from '@/components/MapPoint';
export default {
    components: { MapPoint },
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        facilityList: {
            type: Array,
            default: () => {
                return []
            }
        }
    },
    data() {
        var validateInspectionPointCode = (rule, value, callback) => {
            setTimeout(() => {
                if (!value) {
                    callback(new Error("编号不能为空！！！"));
                } else {
                    var patrn = /[`~!@#$%^&*()\+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）={}|《》？：“”【】、；‘'，。、]/im;
                    if (patrn.test(value)) {
                        callback(new Error("编号不能包含 $、&、￥等特殊字符"));
                        // console.log(value)
                        // 如果包含特殊字符返回false
                    } else {
                        callback();
                    }
                }
            }, 20);
        };
        let validatorNumber = function (rule, value, callback) {
            if (value > 0) {
                callback()
            } else {
                callback(new Error('请输入大于0数值！'))
            }
        }
        let validatorLng = function (rule, lon, callback) {
            if (lon == undefined || lon == null || lon == '') {
                callback(new Error('请输入经度！'))
            } else if (lon < -180 || lon > 180) {
                callback(new Error('请输入-180~180之间数值！'))
            } else {
                callback()
            }
        }
        let validatorLat = function (rule, lat, callback) {
            if (lat == undefined || lat == null || lat == '') {
                callback(new Error('请输入纬度！'))
            } else if (lat < -90 || lat > 90) {
                callback(new Error('请输入-90~90之间数值！'))
            } else {
                callback()
            }
        }
        return {
            loading: false,
            addEditName: '添加',
            addEditApi: '',
            ruleForm: {},
            rules: {
                inspectionPointName: [
                    { required: true, message: '请输入巡查点名称', trigger: 'change' }
                ],
                errorRange: [
                    { required: true, validator: validatorNumber, trigger: 'change' }
                ],
                facilityNoList: [
                    { required: true, message: '请选择设施', trigger: 'change' }
                ],
                inspectionPointCode: [
                    { validator: validateInspectionPointCode, trigger: "change" }
                ],
                longitude: [
                    { required: true, validator: validatorLng, trigger: 'change' }
                ],
                latitude: [
                    { required: true, validator: validatorLat, trigger: 'change' }
                ]
            }
        }
    },
    computed: {

    },
    watch: {
        dialogVisible(v) {
            v && this.initData()
        }
    },

    mounted() { },
    methods: {
        initData() {
            if (this.addEditFlag == 'add') {
                this.ruleForm = {};
                this.resetForm();
                this.addEditApi = patrolInfoManage.addInspectionPointInfo;
                this.addEditName = '添加';
                this.$refs.mapPoint.initMap();
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = { ...this.data };
                this.addEditApi = patrolInfoManage.editInspectionPointInfo;
                this.addEditName = '编辑';

                if (this.data.facilityVOList && this.data.facilityVOList.length > 0) {
                    let facilityNoList = this.data.facilityVOList.map(item => { return item.facilityNo })
                    this.$set(this.ruleForm, 'facilityNoList', facilityNoList)
                }

                let point = [this.data.longitude || '', this.data.latitude || '',]
                let name = this.data.inspectionPointName
                this.loading = true
                setTimeout(() => {
                    this.loading = false;
                    if (name && point.length > 0 && point[0] && point[1]) {
                        this.$refs.mapPoint.toggleMarkerMode(name, point)
                    }
                }, 1000);
            }
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    this.addEditApi({ ...this.ruleForm }).then(res => {
                        this.cancel();
                        this.$message[res.code == 1 ? 'success' : 'warning'](res.code == 1 ? '操作成功' : res.msg || '操作失败')
                    }).catch(err => {
                        console.log(err)
                    })
                } else {
                    return false;
                }
            })
        },
        getMarker(point) {
            this.$set(this.ruleForm, 'longitude', point['lng'] || '')
            this.$set(this.ruleForm, 'latitude', point['lat'] || '')
        },
        //重置
        resetForm() {
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭
        cancel() {
            this.resetForm()
            this.$emit("closeDialog")
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>

<style lang="scss" scoped>
.btn {
    margin-top: 10px;
}

::v-deep .el-dialog {
    margin-top: 5vh !important;
}
</style>